import React, { Component } from 'react'
import { Card } from 'antd'
import styles from './index.module.scss'
import logo from 'assets/logo.png'
import { Form, Input, Button, Checkbox, message } from 'antd'
import { login } from '../../api/user'
import { setToken } from '../../utils/storage'

export default class Login extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: false
    }
  }

  render() {
    console.log(this.props)
    return (
      <div className={styles['login']}>
        <Card className={'login-container'}>
          <img className='login-logo' src={logo} alt='' />
          <Form
            size={'large'}
            name='basic'
            autoComplete='off'
            onFinish={this.onFinish}
            initialValues={{
              mobile: '13911111111',
              code: '246810',
              agree: true
            }}>
            <Form.Item
              name='mobile'
              max={11}
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请正确输入手机号' }
              ]}>
              <Input placeholder='请输入手机号' />
            </Form.Item>

            <Form.Item
              name='code'
              max={6}
              rules={[
                { required: true, message: '请输入验证码' },
                { pattern: /^\d{6}$/, message: '请正确输入验证码' }
              ]}>
              <Input placeholder='请输入验证码' />
            </Form.Item>

            <Form.Item
              name='agree'
              valuePropName='checked'
              rules={[
                {
                  validator: (_, value) => {
                    if (value) {
                      return Promise.resolve()
                    } else {
                      return Promise.reject(new Error('请同意用户协议'))
                    }
                  }
                }
              ]}>
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button block type='primary' htmlType='submit'>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }

  onFinish = async ({ mobile, code }) => {
    // 登录中
    if (this.state.isLoading) return
    this.setState({
      isLoading: true
    })
    const {
      data: { token }
    } = await login({
      mobile,
      code
    }).catch((e) => {
      this.setState({
        isLoading: false
      })
      return Promise.reject(e)
    })
    setToken(token)
    message.success('登录成功', 0.1, () => {
      this.setState({
        isLoading: false
      })
      const pathname = this.props.location?.state?.pathname
      this.props.history.push(pathname || '/home')
    })
  }
}
